﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DisplayTab.Components;
using DisplayTab;
using DisplayTab.Converters;
using System.ComponentModel;
using System.Windows.Threading;
using BetterWpfControls;

namespace DisplayTab
{
    [TemplatePart(Name = "PART_SelectedContentHost", Type = typeof(ContentPresenter))]
    [TemplatePart(Name = "PART_HeaderPanel", Type = typeof(DisplayTabPanel))]
    [TemplatePart(Name = "PART_QuickLinksHost", Type = typeof(SplitButton))]
    public class DisplayTabControl : TabControl
    {
        private Timer timer;
        #region .ctors

        static DisplayTabControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(DisplayTabControl), new FrameworkPropertyMetadata(typeof(DisplayTabControl)));
        }

        public DisplayTabControl()
        {
            Style s = new Style();
            s.Setters.Add(new Setter(UIElement.VisibilityProperty, Visibility.Collapsed));
            ItemContainerStyle = s;
            if (!IsInDesignModeStatic)
            {
                Initialized += new EventHandler(DisplayTabControl_Initialized);
                SelectedIndex = 0;
            }
        }

        void DisplayTabControl_Initialized(object sender, EventArgs e)
        {
            if (DisplayTime > 0)
            {
                timer = new Timer(DisplayTime * 1000);
                timer.Elapsed += new ElapsedEventHandler(ChangeSlide);
                timer.Enabled = true;
            }
        }

        #endregion .ctors

        #region Properties

        private static bool? _isInDesignMode;

        /// <summary>
        /// Gets a value indicating whether the control is in design mode (running in Visual Studio).
        /// </summary>
        public bool IsInDesignModeStatic
        {
            get
            {
                if (!_isInDesignMode.HasValue)
                {
                    var prop = DesignerProperties.IsInDesignModeProperty;
                    _isInDesignMode = (bool)DependencyPropertyDescriptor
                        .FromProperty(prop, typeof(FrameworkElement))
                        .Metadata.DefaultValue;
                }
                return _isInDesignMode.Value;
            }
        }

        private int _tickTime;

        public int DisplayTime
        {
            get { return _tickTime; }
            set { _tickTime = value; }
        }


        #endregion Properties

        #region Methods

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            var tp = Template.FindName("PART_HeaderPanel", this) as DisplayTabPanel;
            if (tp != null)
            {
                tp.SetBinding(DisplayTabPanel.SelectedItemProperty, new Binding(SelectedItemProperty.Name) { Mode = BindingMode.TwoWay, Source = this });
            }
            var sb = Template.FindName("PART_QuickLinksHost", this) as SplitButton;
            if (sb != null)
            {
                if (tp != null)
                {
                    var b = new MultiBinding() { Converter = new BoolToVisibilityConverter() };
                    b.Bindings.Add(new Binding(DisplayTabPanel.IsTruncatingItemsProperty.Name) { Source = tp, Mode = BindingMode.OneWay });
                    sb.SetBinding(FrameworkElement.VisibilityProperty, b);
                }
                sb.SetBinding(SplitButton.ItemsSourceProperty, new Binding("Items") { Mode = BindingMode.OneWay, Source = this });
                if (sb.ItemTemplate == null && sb.GetBindingExpression(SplitButton.ItemTemplateProperty) == null)
                {
                    var factory = new FrameworkElementFactory(typeof(ContentPresenter));
                    factory.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Left);
                    factory.SetBinding(ContentPresenter.ContentProperty, new Binding("Header") { Converter = new WrapVisualConverter() });
                    sb.ItemTemplate = new DataTemplate() { VisualTree = factory };
                }
            }
        }
        protected override DependencyObject GetContainerForItemOverride()
        {
            return new DisplayTabItem();
        }

        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return item is DisplayTabItem;
        }

        void ChangeSlide(object sender, ElapsedEventArgs e)
        {
            this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
            {
                int tabToSelect = (SelectedIndex + 1) % Items.Count;
                SelectedIndex = tabToSelect;
                Console.WriteLine(SelectedIndex);
            }));
        }

        #endregion Methods
    }
}
